package com.zmn.plat.admin.controller.unit;


import com.zmn.common.utils.date.DateUtil;
import com.zmn.mcc.cas.web.StaffAdminService;
import com.zmn.plat.model.entity.base.unit.UnitQuery;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;
import com.zmn.common.dto2.ResponseDTO;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import com.zmn.plat.model.entity.base.unit.Unit;
import com.zmn.plat.services.interfaces.base.unit.UnitService;


/**
 * 基础配置-单位配置表基础修改Controller
 *
 * @author xujie
 * @since 2021-03-01 09:35:57
 */

@Slf4j
@RestController
@RequestMapping("/unit")
public class UnitModifyController {

    @Resource
    private UnitService unitService;

    /**
     * 添加或修改
     * @param unit 操作对象
     * @return ResponseDTO<String>
     */
    @RequestMapping("/addEdit")
    @RequiresPermissions("/unit/addEdit.action")
    public ResponseDTO<String> addEdit(@RequestBody Unit unit) {

        Date now = DateUtil.getNow();
        Integer unitId = unit.getUnitId();
        if (unit.getUnitName() == null) {
            return ResponseDTO.fail("单位名称不能为空！");
        }
        try {
            List<Unit> unitList = unitService.listByQuery(UnitQuery.builder().unitName(unit.getUnitName()).build());
            if (unitList.size() > 0 && !unitList.get(0).getUnitId().equals(unitId)) {
                return ResponseDTO.fail("单位名称：" + unit.getUnitName() + " 已存在！");
            }
            unit.setUpdater(StaffAdminService.currentStaff().getRealName());
            unit.setUpdateTime(now);
            if (unitId == null || unitId == 0 ) {
                unit.setCreater(StaffAdminService.currentStaff().getRealName());
                unit.setCreateTime(now);
                unitService.insert(unit);
            } else {
                unitService.updateByKey(unit);
            }
            return ResponseDTO.success("", "操作成功！");
        } catch (Exception e) {
            log.error("新增/修改失败, Exception{}, msg{}", e, e.getMessage());
            return ResponseDTO.fail("操作失败！");
        }
    }

    /**
     *  批量删除
     *
     * @param unitIdList id 集合
     * @return ResponseDTO<String>
     */
    @ResponseBody
    @RequestMapping(value = "deleteBatch")
    @RequiresPermissions("/unit/deleteBatch.action")
    public ResponseDTO<String> deleteBatch(@RequestBody List<Integer> unitIdList) {

        if (unitIdList == null || unitIdList.size() ==0) {
            return ResponseDTO.fail("请选择要删除的数据！");
        }
        unitService.deleteBatchByKey(unitIdList);
        return ResponseDTO.success("", "删除成功！");
    }

}
